package com.pactera.madp.cp.service.sync.impl;

import cn.hutool.core.util.StrUtil;
import com.pactera.madp.cp.api.dto.sync.SyncDTO;
import com.pactera.madp.cp.api.entity.sync.SyncStateEntity;
import com.pactera.madp.cp.common.constant.Constants;
import com.pactera.madp.cp.common.enums.sync.HrServiceEnum;
import com.pactera.madp.cp.common.enums.sync.SyncTypeEnum;
import com.pactera.madp.cp.context.HandlerContext;
import com.pactera.madp.cp.context.SyncStateContext;
import com.pactera.madp.cp.handler.sync.SyncTypeHandler;
import com.pactera.madp.cp.service.sync.HrPsnSyncBusinessService;
import com.pactera.madp.cp.service.sync.SyncService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class SyncServiceImpl implements SyncService {

    private final RedisTemplate redisTemplate;
    private final HrPsnSyncBusinessService hrPsnSyncBusinessService;
    private final HandlerContext context;

    @Override
    public Boolean handler(SyncDTO dto) {
        // 设置业务流水号
        setSerialNum(dto);

        SyncTypeHandler syncTypeHandler = context.getInstance(dto.getType());
        return syncTypeHandler.handler(dto);
    }

    @Async
    @Override
    public void syncPsnBusiness() {
        SyncStateEntity syncStateEntity = new SyncStateEntity();
        syncStateEntity.setSyncType(SyncTypeEnum.HR.getCode());
        syncStateEntity.setSyncSubType(HrServiceEnum.PSN.getSubType());
        SyncStateContext.set(syncStateEntity);
        try {
            log.info("系统部门回调人员同步业务");
            hrPsnSyncBusinessService.syncBusiness();
        } finally {
            SyncStateContext.remove();
        }
    }

    private void setSerialNum(SyncDTO dto) {
        String serialKey = null;
        if (SyncTypeEnum.HR.getCode().equals(dto.getType())) {
            serialKey = Constants.SYNC_HR_SERIAL_NUM;
        }
        else if (SyncTypeEnum.FINA.getCode().equals(dto.getType())) {
            serialKey = Constants.SYNC_FINA_SERIAL_NUM;
        }
        if (StrUtil.isEmpty(serialKey)) {
            return;
        }
        redisTemplate.opsForValue().set(serialKey, String.valueOf(System.currentTimeMillis()));
    }

}
